package com.example.video.video_server.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.video.common.Constant;
import com.example.video.common.config.RabbitMQ.VideoTranscode;
import com.example.video.common.entity.FileResourceInfo;
import com.example.video.common.util.ResponsEnum;
import com.example.video.common.util.ResponseWrap;
import com.example.video.video_server.entity.VideoResource;
import com.example.video.video_server.service.IVideoResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 消费者
 *
 * @author : yj
 */
@Component
@Slf4j
public class VideoRabbitListenerConfig {

    @Autowired
    private IVideoResourceService iVideoResourceService;

    // 视频资源合并转码响应
    @RabbitListener(queues = VideoTranscode.RESPONSE_QUEUE)
    public void transcodeResponse(String string) {
        ResponseWrap<String> responseWrap = JSONObject.parseObject(string, ResponseWrap.class);
        FileResourceInfo fileResourceInfo = JSONObject.parseObject(JSON.toJSONString(responseWrap.getData()), FileResourceInfo.class);
        VideoResource byId = iVideoResourceService.getById(fileResourceInfo.getRelationId());
        if(byId == null){
            return;
        }
        if (responseWrap.getCode().equals(ResponsEnum.SUCCESS.code)) {
            byId.setUrl(fileResourceInfo.getUrl());
            byId.setBucketName(fileResourceInfo.getBucketName());
//            byId.setObjectName(fileResourceInfo.getObjectName());
            byId.setContentType(fileResourceInfo.getContentType());
            byId.setStatus(Constant.VideoSourceStatus.SUCCESS.value);
        } else {
            byId.setStatus(Constant.VideoSourceStatus.WAITE_TRANSCODE.value);
        }
        iVideoResourceService.updateById(byId);
    }
}
